<template>
  <ManagementLayout title="音色样本管理" subtitle="为角色上传和管理音色样本">

    <!-- 角色选择 -->
    <div class="character-selector">
      <el-select 
        v-model="selectedCharacterId" 
        placeholder="选择角色"
        @change="loadCharacterInfo"
        class="character-select"
      >
        <el-option
          v-for="character in characters"
          :key="character.id"
          :label="character.name"
          :value="character.id"
        />
      </el-select>
    </div>

    <!-- 角色信息 -->
    <div v-if="selectedCharacter" class="magic-form-section">
      <ManagementCard 
        :title="selectedCharacter.name"
        :description="selectedCharacter.description"
        :meta="getCharacterTTSMeta(selectedCharacter)"
      >
        <template #avatar>
          <img 
            :src="selectedCharacter.avatar_url || '/images/avatar.ico'" 
            :alt="selectedCharacter.name"
            @error="e => handleImageError(e)"
            class="magic-avatar"
          />
        </template>
      </ManagementCard>
    </div>

    <!-- 音色样本上传 -->
    <div v-if="selectedCharacter" class="magic-form-section">
      <h3 class="section-title">上传音色样本</h3>
      <p class="section-description">
        上传音频文件来定制角色的音色。支持 WAV、MP3、WEBM、M4A 格式。
        上传后系统会自动切换到 IndexTTS2 引擎。
      </p>
      
      <el-upload
        class="magic-uploader"
        drag
        :before-upload="beforeVoiceUpload"
        :http-request="uploadVoiceSample"
        :show-file-list="false"
        accept=".wav,.mp3,.webm,.m4a"
      >
        <el-icon class="el-icon--upload"><Microphone /></el-icon>
        <div class="el-upload__text">
          将音频文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持 WAV、MP3、WEBM、M4A 格式，文件大小不超过 50MB
          </div>
        </template>
      </el-upload>
    </div>

    <!-- 上传历史 -->
    <div v-if="selectedCharacter && voiceSamples.length > 0" class="magic-form-section">
      <h3 class="section-title">音色样本历史</h3>
      <div class="magic-grid">
        <ManagementCard 
          v-for="sample in voiceSamples" 
          :key="sample.id"
          :title="sample.filename || '音色样本'"
          :meta="getSampleMeta(sample)"
        >
          <template #actions>
            <el-button 
              type="primary" 
              size="small" 
              @click="playSample(sample)"
              :icon="VideoPlay"
            >
              播放
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteSample(sample)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </ManagementCard>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="selectedCharacter && voiceSamples.length === 0" class="empty-state">
      <el-icon size="64" color="#8c939d"><Microphone /></el-icon>
      <p>该角色暂无音色样本</p>
      <p>请上传音频文件来定制音色</p>
    </div>
  </ManagementLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Microphone, VideoPlay, Delete } from '@element-plus/icons-vue'
import { 
  getMyCharacters,
  uploadVoiceSample as uploadVoiceSampleAPI
} from '@/services/api'
import ManagementLayout from './ManagementLayout.vue'
import ManagementCard from './ManagementCard.vue'
import { 
  formatTime, 
  formatFileSize, 
  handleImageError, 
  confirmDelete,
  handleApiError,
  checkFileType,
  checkFileSize
} from '@/utils/managementUtils'

// 响应式数据
const characters = ref([])
const selectedCharacterId = ref(null)
const selectedCharacter = ref(null)
const voiceSamples = ref([])
const uploading = ref(false)

// 加载角色列表
const loadCharacters = async () => {
  try {
    characters.value = await getMyCharacters()
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  }
}

// 加载角色信息
const loadCharacterInfo = async () => {
  if (!selectedCharacterId.value) return
  
  try {
    const character = characters.value.find(c => c.id === selectedCharacterId.value)
    selectedCharacter.value = character
    
    // 这里可以添加加载音色样本历史的逻辑
    // voiceSamples.value = await getVoiceSamples(selectedCharacterId.value)
  } catch (error) {
    ElMessage.error('加载角色信息失败')
  }
}

// 上传前检查
const beforeVoiceUpload = (file) => {
  const allowedTypes = ['audio/wav', 'audio/mp3', 'audio/webm', 'audio/mp4']
  const isAllowedType = allowedTypes.includes(file.type) || 
    file.name.toLowerCase().match(/\.(wav|mp3|webm|m4a)$/)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isAllowedType) {
    ElMessage.error('只支持 WAV、MP3、WEBM、M4A 格式的音频文件!')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB!')
    return false
  }
  return true
}

// 上传音色样本
const uploadVoiceSample = async (options) => {
  try {
    uploading.value = true
    
    const response = await uploadVoiceSampleAPI(selectedCharacterId.value, options.file)
    
    ElMessage.success('音色样本上传成功')
    
    // 更新角色信息
    await loadCharacterInfo()
    
    // 这里可以添加刷新音色样本列表的逻辑
    // await loadVoiceSamples()
    
  } catch (error) {
    ElMessage.error('上传音色样本失败')
  } finally {
    uploading.value = false
  }
}

// 播放音色样本
const playSample = (sample) => {
  // 这里可以添加播放音频的逻辑
  ElMessage.info('播放功能待实现')
}

// 获取角色TTS元信息
const getCharacterTTSMeta = (character) => {
  const meta = []
  if (character.tts_engine) meta.push(`TTS引擎: ${character.tts_engine}`)
  if (character.voice_id) meta.push(`音色ID: ${character.voice_id}`)
  return meta
}

// 获取样本元信息
const getSampleMeta = (sample) => {
  const meta = []
  if (sample.size) meta.push(formatFileSize(sample.size))
  if (sample.created_at) meta.push(formatTime(sample.created_at))
  return meta
}

// 删除音色样本
const deleteSample = async (sample) => {
  try {
    await confirmDelete(sample.filename || '音色样本', '音色样本')
    
    // 这里可以添加删除音色样本的API调用
    // await deleteVoiceSample(sample.id)
    
    ElMessage.success('音色样本删除成功')
    await loadCharacterInfo()
  } catch (error) {
    if (error !== 'cancel') {
      handleApiError(error, '删除音色样本失败')
    }
  }
}


// 组件挂载时加载数据
onMounted(() => {
  loadCharacters()
})
</script>

<style scoped>
@import '@/styles/management-common.css';

.character-selector {
  margin-bottom: 30px;
  text-align: center;
}

.character-select {
  width: 300px;
}
</style>
